package models

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/astaxie/beego/orm"
	"strconv"
)

//由于model这个名字叫 FenceInfo 那么操作的表其实 fence_info
type FenceInfo struct {
	Id int64
	Fenceid string
	Fencename string
	Fencepoint string
	Company string
	Department string
}


//添加电子围栏
func AddFence(fence_info *FenceInfo)(int64,error){
	db := orm.NewOrm()
	id,err := db.Insert(fence_info)
	return id,err
}

//查询所有的电子围栏
func ReadFence(fencedatachan chan string,company string, page string,size string)int {
	var fencerows []FenceInfo
	o := orm.NewOrm()
	pageint, _ := strconv.ParseInt(page, 10, 64)
	sizeint, _ := strconv.ParseInt(size, 10, 64)
	var totalItem int = 0
	o.Raw("SELECT COUNT(*) FROM fence_info where company = ? ", company).QueryRow(&totalItem)
	//fmt.Println(totalItem)
	if _, err := o.Raw("SELECT * FROM fence_info where company = ?  limit ?,?", company, (pageint-1)*sizeint, sizeint).QueryRows(&fencerows); err != nil {
		fmt.Println("err")
		return 0
	}

	var  i int64= (pageint-1)*sizeint;
	for _,fencerow := range fencerows{
		i++
		id := strconv.FormatInt(i,10)
		fenceInfos :=id+ "and"+ fencerow.Fenceid+
			"and"+fencerow.Fencename+
			//"and"+fencerow.Fencepoint+
			"and"+fencerow.Company+
			"and"+fencerow.Department
		fencedatachan <- fenceInfos
	}
	return totalItem
}



//查看某一个电子围栏坐标
func ReadOneFence(fencedatachan chan string,company string, fenceid string) {
	var fencerows []FenceInfo
	o := orm.NewOrm()

	//fmt.Println(totalItem)
	if _, err := o.Raw("SELECT * FROM fence_info where company = ?  and fenceid = ?", company,fenceid).QueryRows(&fencerows); err != nil {
		fmt.Println("err")
	}

	for _,fencerow := range fencerows{
		fenceInfos :=fencerow.Fenceid+
			"and"+fencerow.Fencepoint
		fencedatachan <- fenceInfos
		break
	}
}



//查看某一个电子围栏
func ReadALLFence(fencedatachan chan string,company string) {
	var fencerows []FenceInfo
	o := orm.NewOrm()

	//fmt.Println(totalItem)
	if _, err := o.Raw("SELECT * FROM fence_info where company = ?  ", company,).QueryRows(&fencerows); err != nil {
		fmt.Println("err")
	}

	for _,fencerow := range fencerows{
		fenceInfos :=fencerow.Fencename+
			"and"+fencerow.Fencepoint
		fencedatachan <- fenceInfos
	}
}


